package com.farm.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.farm.entity.Product;
import com.farm.entity.User;
import com.farm.repository.ProductRepository;

@Service
public class ProductService {
    private static final Logger logger = LoggerFactory.getLogger(ProductService.class);

    @Autowired
    private ProductRepository productRepository;

    @Transactional
    public Product createProduct(Product product) {
        logger.debug("Creating new product: {}", product.getName());
        product.setApproved(false);
        return productRepository.save(product);
    }

    @Transactional
    public Product approveProduct(Long productId) {
        logger.debug("Approving product with ID: {}", productId);
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("Product not found"));
        product.setApproved(true);
        return productRepository.save(product);
    }

    @Transactional
    public Product updateProduct(Product product) {
        logger.debug("Updating product with ID: {}", product.getId());
        Product existingProduct = productRepository.findById(product.getId())
                .orElseThrow(() -> new RuntimeException("Product not found"));
        
        existingProduct.setName(product.getName());
        existingProduct.setDescription(product.getDescription());
        existingProduct.setPrice(product.getPrice());
        existingProduct.setCategory(product.getCategory());
        existingProduct.setStock(product.getStock());
        if (product.getImage() != null) {
            existingProduct.setImage(product.getImage());
        }
        
        return productRepository.save(existingProduct);
    }

    @Transactional
    public void deleteProduct(Long productId) {
        logger.debug("Deleting product with ID: {}", productId);
        productRepository.deleteById(productId);
    }

    public List<Product> findByFarmer(User farmer) {
        logger.debug("Finding products by farmer: {}", farmer.getUsername());
        return productRepository.findByFarmer(farmer);
    }

    public List<Product> findByCategory(String category) {
        logger.debug("Finding products by category: {}", category);
        return productRepository.findByCategoryAndApproved(category, true);
    }

    public List<Product> findPendingProducts() {
        logger.debug("Finding pending products");
        return productRepository.findByApproved(false);
    }

    public List<Product> findApprovedProducts() {
        logger.debug("Finding approved products");
        return productRepository.findByApproved(true);
    }

    public List<Product> findAllProducts() {
        logger.debug("Finding all products");
        return productRepository.findAll();
    }

    public List<Product> searchProducts(String keyword, String category, Boolean approved) {
        logger.debug("Searching products with keyword: {}, category: {}, approved: {}", keyword, category, approved);
        try {
            if (keyword != null && !keyword.trim().isEmpty()) {
                if (category != null && !category.trim().isEmpty()) {
                    if (approved != null) {
                        return productRepository.findByNameContainingAndCategoryAndApproved(keyword, category, approved);
                    }
                    return productRepository.findByNameContainingAndCategory(keyword, category);
                }
                if (approved != null) {
                    return productRepository.findByNameContainingAndApproved(keyword, approved);
                }
                return productRepository.findByNameContaining(keyword);
            }
            
            if (category != null && !category.trim().isEmpty()) {
                if (approved != null) {
                    return productRepository.findByCategoryAndApproved(category, approved);
                }
                return productRepository.findByCategory(category);
            }
            
            if (approved != null) {
                return productRepository.findByApproved(approved);
            }
            
            return productRepository.findAll();
        } catch (Exception e) {
            logger.error("Error searching products", e);
            throw new RuntimeException("搜索产品时发生错误: " + e.getMessage());
        }
    }

    public Product findById(Long productId) {
        logger.debug("Finding product by ID: {}", productId);
        return productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("Product not found"));
    }
} 